// import native from './jsbridge'
import { Toast } from 'antd-mobile'

export default {
  requestTransform(isEncrypt) {
    return function (data) {
      if (isEncrypt) {
        return native.encrypt({ data }).then(function (res) {
          return res
        })
      } else {
        return data
      }
    }
  },
  responseTransform() {
    return function (data) {
      if (typeof data === 'object') {
        return data
      }
      let canBeParse = true
      try {
        data = JSON.parse(data)
      } catch (error) {
        canBeParse = false
      }
      if (canBeParse) {
        return data
      } else {
        return native.decrypt({ data }).then(function (res) {
          try {
            res = decodeURIComponent(res)
          } catch (e) {
            console.error('decodeURIComponent失败：', res)
            console.error(e)
          }

          let result = {}
          try {
            result = JSON.parse(res)
          } catch (err) {
            Toast.info('解密报文JSON转换失败！' + err, 2)
          }

          return result
        })
      }
    }
  }
}
